package divtastic;

class DispatchTo
{
    
    private var func0:                          Void -> Void ;
    private var times0:                         Int;
    
    private var func:                           Array<Void -> Void> ;
    private var times:                          Array<Int> ;
    public var length( get_length, null ):      Int ;
    
    
    private function get_length(): Int
    {
        
        return func.length;
        
    }
    
    
    public function new()
    {
        
        func    = new Array() ;
        times   = new Array() ;
        
    }
    
    
    public function add( f_: Void -> Void, ?once: Bool, ?amount: Int )
    {
        
        func.push( f_ ) ;
        
        if( once != null )
        {
            
            if( true )
            {
                
                times.push( 1 ) ;
                
            }
            else
            {
                
                times.push( -1 ) ;
                
            }
            
        }
        else if( amount != null )
        {
            
            times.push( amount ) ;
            
        }
        else
        {
            
            times.push( -1 ) ;
            
        }
        
    }
    
    
    public function remove( f_: Void -> Void )
    {
        
        for( i in 0...func.length )
        {
            
            if( func[ i ] == f_ )
            {
                
                func.splice( i, 1 ) ;
                times.splice( i, 1 ) ;
                
            }
            
        }
        
    }
    
    
    public function dispatch()
    {
        
        var count: Int ;
        
        for( i in 0...func.length )
        {
            
            func[ i ]() ;
            count       = times[ i ] ;
            
            if( count == -1 )
            {
                
                // don't remove if -1 as implies infinite Signal use untill removed.
                
            }
            else
            {
                
                count--;
                times[ i ]  = count ;
                
                if( count == 0 )
                {
                
                    func.splice( i, 1 ) ;
                    times.splice( i, 1 ) ;
                
                }
                
            }
            
        }
        
    }
    
}